package com.block.datapush.special.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.model.result.ApiPushResult;
import com.block.datapush.special.api.utils.HaoHanUtil;
import com.block.datapush.special.enums.OrderStatusEnum;
import com.block.datapush.special.service.IApiPushService;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.MemberPushOrderInfo;
import com.block.db.entity.SpecialCostomInfo;
import com.block.db.entity.SpecialDataApiInfo;
import com.block.db.mapper.MemberPushOrderInfoMapper;
import com.block.db.mapper.SpecialDataApiInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
@Service
public class HaoHanApiService implements IApiPushService {
    private static final Logger log = LogFactory.getPushLog();
    @Value("${market.protocol.hostUrl}")
    private String protocolHostUrl;
    @Resource
    MemberPushOrderInfoMapper memberPushOrderInfoMapper;

    @Override
    public ApiPushResult matchUser(String orderNo, SpecialCostomInfo costomInfo, MemberExtInfo memberExtInfo, JSONObject jsonObject) throws Exception {

        String queryUrl = costomInfo.getApiMatchUrl();

        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("appid",costomInfo.getApiCode());
        paramMap.put("name_md5", SecureUtil.md5(memberExtInfo.getUsername()).toLowerCase());
        paramMap.put("idno_md5", SecureUtil.md5(memberExtInfo.getIdCard()).toLowerCase());
        paramMap.put("phone_md5", SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase());
        paramMap.put("age", Integer.toString(memberExtInfo.getAge()));
        paramMap.put("sex", HaoHanUtil.getSex(memberExtInfo.getSex()));
        paramMap.put("ip", memberExtInfo.getReqIp());
        paramMap.put("working_city", memberExtInfo.getProvince() + "/" + memberExtInfo.getCity());

        //页面要求
        paramMap.put("salary_type", "银行代发");
        paramMap.put("loan_amount", HaoHanUtil.getLoanAmount(memberExtInfo.getLoanAmount()));
        paramMap.put("loan_period", memberExtInfo.getLoanTime() + "个月");
        paramMap.put("reserved_funds", HaoHanUtil.getGjj(memberExtInfo.getGjj()));
        paramMap.put("social_security", HaoHanUtil.getShebao(memberExtInfo.getSocialInsurance()));
        paramMap.put("credit_record", HaoHanUtil.getXinyong(memberExtInfo.getYuqi()));
        paramMap.put("insurance", HaoHanUtil.getInsurance(memberExtInfo.getInsurance()));
        paramMap.put("real_estate", HaoHanUtil.getHouse(memberExtInfo.getHouse()));
        paramMap.put("zhima", HaoHanUtil.getZhiMa(memberExtInfo.getZhimaScore()));
        paramMap.put("car", HaoHanUtil.getCar(memberExtInfo.getCar()));
        paramMap.put("industry", HaoHanUtil.getJob(memberExtInfo.getJob()));
        paramMap.put("loan_lately", "没有申请过贷款");
        paramMap.put("phone_pre", memberExtInfo.getMobile().substring(0, 3));

        //接口要求
//        paramMap.put("salary_type",BaseTypeInfoEnum.HaoHanSalary.getNameByValue(memberExtInfo.getSalary()));
//        paramMap.put("load_amount", BaseTypeInfoEnum.LoanAmount.getNameByValue(memberExtInfo.getLoanAmount()));
//        paramMap.put("loan_period",memberExtInfo.getLoanTime()+"月");
//        paramMap.put("reserved_funds",BaseTypeInfoEnum.Gjj.getNameByValue(memberExtInfo.getGjj()));
//        paramMap.put("social_security",BaseTypeInfoEnum.SocialInsurance.getNameByValue(memberExtInfo.getSocialInsurance()));
//        paramMap.put("credit_record",BaseTypeInfoEnum.Yuqi.getNameByValue(memberExtInfo.getYuqi()));
//        paramMap.put("insurance",BaseTypeInfoEnum.Insurance.getNameByValue(memberExtInfo.getInsurance()));
//        paramMap.put("real_estate",BaseTypeInfoEnum.House.getNameByValue(memberExtInfo.getHouse()));
//        paramMap.put("zhima",HaoHanUtil.getZhiMa(memberExtInfo.getZhimaScore()));
//        paramMap.put("car",BaseTypeInfoEnum.Car.getNameByValue(memberExtInfo.getCar()));
//        paramMap.put("industry",BaseTypeInfoEnum.Job.getNameByValue(memberExtInfo.getJob()));
//        paramMap.put("loan_lately","没有申请过贷款");
//        paramMap.put("phone_pre",memberExtInfo.getMobile().substring(0,3));


        log.info("【浩瀚有借】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【浩瀚有借】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        System.out.println("resultObject=="+resultObject);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        ApiPushResult apiPushResult = new ApiPushResult();

        if (StrUtil.equals(code, "0")) {


            JSONArray list = resultObject.getJSONArray("list");
            for (int i = 0; i < list.size(); i++) {
                JSONObject product = list.getJSONObject(i);
                JSONArray protocols = product.getJSONArray("protocols");

                for (int j = 0; j < protocols.size(); j++) {
                    JSONObject protocol = protocols.getJSONObject(j);
                    String value = protocol.getString("value");
                    apiPushResult.setSkipUrl(value);//撞库返回的订单号
                    System.out.println("Protocol Value: " + value);
                    break ;
                }
            }

            apiPushResult.setTid(resultObject.getString("tid"));//撞库返回的订单号
            apiPushResult.setSuccess(true);
            return apiPushResult;
        }else {
            apiPushResult.setSuccess(false);
            apiPushResult.setStatus(OrderStatusEnum.FAILED.getValue());
            apiPushResult.setMessage(msg);
            return apiPushResult;
        }
    }

    @Override
    public ApiPushResult register(String orderNo, SpecialCostomInfo costomInfo, MemberExtInfo memberExtInfo, JSONObject jsonObject) throws Exception {
        ApiPushResult apiPushResult = new ApiPushResult();
        apiPushResult.setOrderNo(orderNo);
        // order_no: ml_special_data_api_info表的id

        String requestUrl = costomInfo.getApiRegisterUrl();
        LocalDateTime now = LocalDateTime.now();

        String protocolUrl = jsonObject.getString("skip_url");
        System.out.println("stirng-order_info_id=="+protocolUrl);
//        String protocolUrl = StrUtil.format(protocolHostUrl, order_info_id);
        // 授权协议信息
        List<String> authorizeUrls = Arrays.asList(protocolUrl);
//        List<String> authorizeUrls = Arrays.asList("电子签协议URL", protocolUrl);

        Map<String, Object> thirdInfo = new HashMap<>();
        thirdInfo.put("name", memberExtInfo.getUsername());
        thirdInfo.put("phone", memberExtInfo.getMobile());
        thirdInfo.put("idno", memberExtInfo.getIdCard());
        thirdInfo.put("authorize_time", LocalDateUtil.getDateFormatStr(now, LocalDateUtil.TOTAL_DATE_TIME));
        thirdInfo.put("authorize", authorizeUrls);

        Map<String, Object> bizMap = new HashMap<>();

        String uuid = jsonObject.getString("uuid");
        System.out.println("stirng-uuid=="+uuid);
        bizMap.put("uuid", uuid);
        bizMap.put("thirdInfo", thirdInfo);

        log.info("【浩瀚有借】导单开始【requestUrl】{}【bizMap】{}", requestUrl, JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【浩瀚有借】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        apiPushResult.setResult(JSON.toJSONString(resultObject));
        apiPushResult.setCode(String.valueOf(code));
        apiPushResult.setMessage(msg);
        apiPushResult.setBizParam(JSON.toJSONString(bizMap));

        if (StrUtil.equals(code, "0")) {
            apiPushResult.setSuccess(true);
            apiPushResult.setSettleFlag(true);
            apiPushResult.setStatus(OrderStatusEnum.SUCCESS.getValue());
            return apiPushResult;
        }

        apiPushResult.setSuccess(false);
        apiPushResult.setStatus(OrderStatusEnum.FAILED.getValue());
        return apiPushResult;
    }

    @Override
    public ApiPushResult queryResult(SpecialCostomInfo costomInfo, SpecialDataApiInfo dataApiInfo, JSONObject jsonObject) {
        return null;
    }
}
